package com.seeyon.apps.kk.manager;

import java.io.File;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import www.seeyon.com.utils.StringUtil;

import com.google.common.collect.Maps;
import com.seeyon.apps.addressbook.manager.AddressBookCustomerFieldInfoManager;
import com.seeyon.apps.addressbook.manager.AddressBookManager;
import com.seeyon.apps.addressbook.po.AddressBook;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.dao.SyncOrgDao;
import com.seeyon.apps.kk.util.CsvHandler;
import com.seeyon.apps.kk.util.ErrorMessageUtil;
import com.seeyon.apps.kk.util.SFtpHandler;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.config.manager.ConfigManager;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.metadata.bo.MetadataColumnBO;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumBean;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.OrganizationMessage;
import com.seeyon.ctp.organization.bo.OrganizationMessage.OrgMessage;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgLevel;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.Datetimes;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.ctp.util.Strings;
import com.seeyon.v3x.worktimeset.manager.WorkTimeManager;

public class QiangsMemberManagerImpl implements QiangsMemberManager {

	private static final Log log = LogFactory.getLog(QiangsMemberManagerImpl.class);

   /* private ColManager colManager;
    private AffairManager affairManager;
    private RestUserManager restUserManager;
    private CAP4FormRelationRecordDAO cap4FormRelationRecordDAO;
    private CAP4FormBusinessRelationDAO cap4FormBusinessRelationDAO;
    private MessageMailManager messageMailManager;
    private CAP4FormBusinessRelationManager cap4FormBusinessRelationManager;*/
    
    private OrgManager orgManager;
    private SyncOrgDao baseQiangsDao;
    private FormApi4Cap4 formApi4Cap4;
    private EnumManager enumManagerNew;
    private ConfigManager configManager;
    private WorkTimeManager workTimeManager;
    private OrgManagerDirect orgManagerDirect;
    private FormDataBaseManager kkBaseFormManager;
    protected AddressBookManager addressBookManager;
    protected AddressBookCustomerFieldInfoManager addressBookCustomerFieldInfoManager;

    @Override
    public void syncFile4Ftp() throws BusinessException {
        // TODO Auto-generated method stub
        Map<String, Object> logMap = new HashMap<String, Object>();
        try {
            if (Strings.isNotEmpty(Constants.HOST) && Strings.isNotEmpty(Constants.FTPNAME)
                    && Strings.isNotEmpty(Constants.FTPPWD) && Strings.isNotEmpty(Constants.PORT)) {
                SFtpHandler ftp = new SFtpHandler(Constants.HOST, Integer.valueOf(Constants.PORT).intValue(),
                        Constants.FTPNAME, Constants.FTPPWD);
                File file = ftp.getFile();
                //ftp下载日志s
                if (null == file) {
                    logMap.put("日期", DateUtil.currentDate());
                    logMap.put("结果", "失败");
                    logMap.put("说明", "人员主数据从ftp下载失败.");
                } else {
                    logMap.put("日期", DateUtil.currentDate());
                    logMap.put("结果", "成功");
                    logMap.put("说明", "人员主数据从ftp下载成功.");

                    List<String[]> list = CsvHandler.handler(file.getPath());
                    List<Map> logList = new ArrayList<Map>();
                    for (String[] row : list) {
                        Map subMap = new HashMap();
                        String deptCode = row[22];
                        String levelCode = row[56];
                        String postCode = row[88];
                        String id = row[0];
                        FlipInfo flipInfo = new FlipInfo(1, 20);
                        FormBean bean = formApi4Cap4.getFormByFormCode(Constants.memberFormCode);
                        Map<String, Object> where = new HashMap<String, Object>();
                        where.put(bean.getFieldBeanByDisplay("EmployeeID").getName(), id);
                        List<FormDataMasterBean> masterList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, where);
                        Map<String, Object> param = convert2Map(row);
                        if (CollectionUtils.isEmpty(masterList)) {
                            //新增
                            Long yes = getEnumItemIdByName("通用类", "是否", "是");
                            param.put("是否进行同步", yes);
                            Long masterId = kkBaseFormManager.saveUnflowData(Constants.memberFormCode, Constants.createUser, param);
                            subMap.put("EmployeeID", param.get("EmployeeID"));
                            subMap.put("FirstNameinLocalScript", param.get("FirstNameinLocalScript"));
                            subMap.put("LastNameinLocalScript", param.get("LastNameinLocalScript"));
                            subMap.put("备注", "人员新增.");
                            logList.add(subMap);
                        } else {
                            //修改
                            FormDataMasterBean dataBean = masterList.get(0);
                            String content = kkBaseFormManager.updateFormData(Constants.memberFormCode, dataBean, param);
//                            String content = updateFormData(Constants.memberFormCode, masterList.get(0), param);
                            if (Strings.isNotEmpty(content)) {
                                subMap.put("EmployeeID", param.get("EmployeeID"));
                                subMap.put("FirstNameinLocalScript", param.get("FirstNameinLocalScript"));
                                subMap.put("LastNameinLocalScript", param.get("LastNameinLocalScript"));
                                subMap.put("备注", content);
                                logList.add(subMap);
                            }
                        }
                    }
                    if (CollectionUtils.isNotEmpty(logList)) {
                        logMap.put("subData", logList);
                    }
                }
            } else {
                logMap.put("日期", DateUtil.currentDate());
                logMap.put("结果", "失败");
                logMap.put("说明", "未配置ftp参数.");
            }
            //保存同步日志
            kkBaseFormManager.saveUnflowData(Constants.memberLogCode, Constants.createUser, logMap);
//            saveFormData(Constants.memberLogCode, logMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        }
    }

    @Override
    public void syncMemberInfo() throws BusinessException {
        try {
            Thread.sleep(10 * 1000L);

            //进行人员同步
            FormBean formBean = formApi4Cap4.getFormByFormCode(Constants.memberFormCode);
            Long terminated = getEnumItemIdByName("人员枚举", "Terminated", "Terminated");
            Long maleId = getEnumItemIdByName("人员枚举", "Gender", "Male");
            V3xOrgPost post = baseQiangsDao.getPostByCode(Constants.DEFAULT_ACCOUNT_ID, "code", Constants.DEFAULTCODE);
            V3xOrgLevel level = baseQiangsDao.getLevelByCode(Constants.DEFAULT_ACCOUNT_ID, "code", Constants.DEFAULTCODE);
            V3xOrgDepartment dept = baseQiangsDao.getDeptByCode(Constants.DEFAULT_ACCOUNT_ID, "code", Constants.DEFAULTCODE);
            V3xOrgDepartment OCDDept = baseQiangsDao.getDeptByCode(Constants.DEFAULT_ACCOUNT_ID, "code", Constants.DEPT_OCD);
            String password = configManager.getConfigItem("system_switch", "initPassword").getConfigValue().toString();
            Map<String, Long> initMap = new HashMap<String, Long>();
            initMap.put("terminated", terminated);
            initMap.put("maleId", maleId);
            initMap.put("post", post.getId());
            initMap.put("level", level.getId());
            initMap.put("dept", dept.getId());
            initMap.put("ocd_dept", OCDDept.getId());

            boolean isLoop = true;
            FlipInfo flipInfo = new FlipInfo(1, 200);
            Map<String, Object> condition = new HashMap<String, Object>();
            Long yes = getEnumItemIdByName("通用类", "是否", "是");
            condition.put(formBean.getFieldBeanByDisplay("是否进行同步").getName(), yes);
            List<FormDataMasterBean> members = formApi4Cap4.findMasterDataList(flipInfo, formBean.getId(), null, condition);
            
            List<V3xOrgDepartment> ocdSubDeparts = orgManager.getChildDepartments(initMap.get("ocd_dept"), false);
			Map<Long, Long> departsAnddeptLeaderMap = Maps.newHashMap();
			for(int i=0; i<ocdSubDeparts.size(); i++) {
				List<V3xOrgMember> memberlist = this.orgManager.getMembersByRole(ocdSubDeparts.get(i).getId(), -1726439953579618944L);
				if(memberlist!= null && memberlist.size() != 0) {
					departsAnddeptLeaderMap.put(ocdSubDeparts.get(i).getId(), memberlist.get(0).getId());
				}
			}

            while (isLoop) {
                //循环获取人员主数据
                if (flipInfo.getPage() != 1) {
                    members = formApi4Cap4.findMasterDataList(flipInfo, formBean.getId(), null, condition);
                    if (CollectionUtils.isEmpty(members) || members.size() <= 199) {
                        isLoop = false;
                    }
                }
                flipInfo.setPage(flipInfo.getPage() + 1);

                //同步人员账号信息
                for (FormDataMasterBean dataBean : members) {
                    String code = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("EmployeeID").getName()).toString();
                    V3xOrgMember member = baseQiangsDao.getMemberByCode(Constants.DEFAULT_ACCOUNT_ID, "code", code);
                    if (null == member) {
                        // 新建人员
                        try {
                            //底表数据与人员数据的状态都为停用,则不进行同步
                            if (terminated.toString().equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Terminated").getName()).toString())) {
                                dataBean.addFieldValue(formBean.getFieldBeanByDisplay("上次同步时间").getName(), DateUtil.currentDate());
                                dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(), "状态为:Terminated,不执行人员新增.");
                                formApi4Cap4.saveOrUpdateFormData(dataBean, formBean.getId(), true);
                                continue;
                            }
                            member = new V3xOrgMember();
                            if (null == dataBean.getFieldValue(formBean.getFieldBeanByDisplay("EmailAddress").getName())) {
                                dataBean.addFieldValue(formBean.getFieldBeanByDisplay("上次同步时间").getName(), DateUtil.currentDate());
                                dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(),
                                        "邮箱为空,新增人员失败!");
                                formApi4Cap4.saveOrUpdateFormData(dataBean, formBean.getId(), true);
                                continue;
                            }
                            map2Member(member, formBean, initMap, dataBean, departsAnddeptLeaderMap);
                            OrganizationMessage mes = orgManagerDirect.addMember(member);

                            List<OrgMessage> errorMsgList = mes.getErrorMsgs();
                            if (errorMsgList.size() > 0) {
                                dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(),
                                        ErrorMessageUtil.getErrorMessageString(errorMsgList));
                            } else {
                                dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(), "新增成功.");
                            }
                            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("上次同步时间").getName(), DateUtil.currentDate());
                            formApi4Cap4.saveOrUpdateFormData(dataBean, formBean.getId(), true);
                        } catch (Exception e) {
                            log.error("##强生客开: ", e);
                            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("上次同步时间").getName(), DateUtil.currentDate());
                            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(),
                                    "新增异常:  请查询ctp.log日志文件.");
                            formApi4Cap4.saveOrUpdateFormData(dataBean, formBean.getId(), true);
                        }
                    } else {
                        // 修改人员信息
                        member = orgManager.getMemberById(member.getId());
                        boolean isUpdate = data2UpdateMember(member, formBean, initMap, dataBean, departsAnddeptLeaderMap);
                        try {
                            if (isUpdate) {
                                OrganizationMessage mes = orgManagerDirect.updateMember(member);
                                List<OrgMessage> errorMsgList = mes.getErrorMsgs();
                                if (errorMsgList.size() > 0) {
                                    dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(),
                                            ErrorMessageUtil.getErrorMessageString(errorMsgList));
                                }
                                formApi4Cap4.saveOrUpdateFormData(dataBean, formBean.getId(), true);
                            }
                        } catch (Exception e) {
                            log.error("##强生客开: ", e);
                            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(),
                                    "新增异常:  请查询ctp.log日志文件.");
                            formApi4Cap4.saveOrUpdateFormData(dataBean, formBean.getId(), true);
                        }
                    }
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            log.error("##强生客开: ", e);
        }
    }

    private Long getEnumItemIdByName(String parentName, String sonName, String subName) throws BusinessException {
        List<String> vlist = new ArrayList<String>();
        vlist.add(parentName);
        Map condition = new HashMap();
        condition.put("enumNames", vlist);
        condition.put("accountId", Constants.DEFAULT_ACCOUNT_ID);
        condition.put("enumType", 3);
        List<CtpEnumBean> list = enumManagerNew.findEnumList(condition);
        if (CollectionUtils.isNotEmpty(list)) {
            for (CtpEnumBean enumBean : list) {
                vlist = new ArrayList<String>();
                vlist.add(sonName);
                condition.put("enumType", 0);
                condition.put("parentId", enumBean.getId());
                condition.put("enumNames", vlist);
                List<CtpEnumBean> sonList = enumManagerNew.findEnumList(condition);
                if (CollectionUtils.isNotEmpty(sonList)) {
                    Long parentId = sonList.get(0).getId();
                    if (StringUtil.isEmpty(subName)) {
                        return parentId;
                    } else {
                        for (CtpEnumItem item : enumManagerNew.getCtpEnumItem(sonList.get(0).getId(), 0)) {
                            if (subName.equals(item.getShowvalue())) {
                                return item.getId();
                            }
                        }
                        return null;
                    }
                } else {
                    CtpEnumItem item = null;
                    for (CtpEnumItem it : enumManagerNew.getCtpEnumItem(enumBean.getId(), 0)) {
                        if (sonName.equals(it.getShowvalue())) {
                            item = it;
                            break;
                        }
                    }

                    if (StringUtil.isEmpty(subName)) {
                        return item.getId();
                    } else {
                        for (CtpEnumItem it : enumManagerNew.getChildEnumItems(item.getId())) {
                            if (subName.equals(it.getShowvalue())) {
                                return it.getId();
                            }
                        }
                        return null;
                    }
                }
            }
        }
        return null;
    }

    private Map convert2Map(String[] row) throws BusinessException, ParseException {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("EmployeeID", row[0]);
        param.put("FirstName", row[1]);
        param.put("MiddleName", row[2]);
        param.put("LastName", row[3]);
        param.put("FirstNameinLocalScript", row[7]);
        param.put("LastNameinLocalScript", row[9]);
        //枚举
        if ("Female".equals(row[16])) {
            Long femaleId = getEnumItemIdByName("人员枚举", "Gender", "Female");
            param.put("Gender", femaleId);
        } else {
            Long maleId = getEnumItemIdByName("人员枚举", "Gender", "Male");
            param.put("Gender", maleId);
        }
        param.put("BirthDate", getActiveDate(row[17]));
        param.put("AddressLineData", row[26]);
        param.put("Municipality", row[27]);
        param.put("Submunicipality", row[28]);
        param.put("Region", row[29]);
        param.put("PostalCode", row[31]);
        param.put("Country", row[32]);
        param.put("InternationalPhoneCode", row[53]);
        param.put("PhoneAreaCode", row[54]);
        param.put("PhoneNumber", row[55]);
        param.put("PhoneExtension", row[56]);
        param.put("InternationalPhoneCode2", row[59]);
        param.put("PhoneAreaCode2", row[60]);
        param.put("PhoneNumber2", row[61]);
        param.put("PhoneExtension2", row[62]);
        param.put("EmailAddress", row[64]);
        param.put("HireDate", getActiveDate(row[65]));
        param.put("OriginalHireDate", getActiveDate(row[66]));
        param.put("ContinuousServiceDate", getActiveDate(row[67]));
        //
        if ("Terminated".equals(row[68])) {
            Long terminated = getEnumItemIdByName("人员枚举", "Terminated", "Terminated");
            param.put("Terminated", terminated);
        } else {
            Long notTerminated = getEnumItemIdByName("人员枚举", "Terminated", "Not Terminated");
            param.put("Terminated", notTerminated);
        }
        param.put("TerminationDate", getActiveDate(row[69]));
        //
        if ("FALSE".equals(row[73])) {
            Long terminated = getEnumItemIdByName("人员枚举", "RegrettableTermination", "FALSE");
            param.put("RegrettableTermination", terminated);
        } else {
            Long notTerminated = getEnumItemIdByName("人员枚举", "RegrettableTermination", "Not TRUE");
            param.put("RegrettableTermination", notTerminated);
        }
        param.put("ResignationDate", getActiveDate(row[75]));
        param.put("PositionID", row[78]);
        param.put("PositionTitle", row[80]);
        param.put("BusinessTitle", row[82]);
        param.put("JobProfileID", row[89]);
        param.put("JobProfileName", row[90]);
        param.put("JobFamily", row[91]);
        param.put("ManagerWWID", row[93]);
        param.put("ManagerName", row[94]);
        param.put("SupervisorOrgID", row[95]);
        param.put("SupervisorOrgName", row[96]);
        //
        if ("InActive".equals(row[100])) {
            Long terminated = getEnumItemIdByName("人员枚举", "Status", "InActive");
            param.put("Status", terminated);
        } else {
            Long notTerminated = getEnumItemIdByName("人员枚举", "Status", "Active");
            param.put("Status", notTerminated);
        }
        param.put("CompensationGrade", row[139]);
        param.put("CompensationGradeProfile", row[140]);
        param.put("COMPANY", row[141]);
        param.put("COST_CENTER", row[142]);
        param.put("EMPLOYEE_FUNCTION", row[143]);
        param.put("LOCATION_HIERARCHY", row[144]);
        param.put("MRC_FOR_HEADCOUNT", row[145]);
        param.put("REGION", row[146]);
        param.put("SUPERVISORY", row[147]);
        param.put("SupervisoryOrgName", row[148]);
        param.put("WorkLocationID", row[153]);
        //
        if ("English (United States)".equals(row[155])) {
            Long terminated = getEnumItemIdByName("人员枚举", "LanguagePreference", "English (United States)");
            param.put("LanguagePreference", terminated);
        } else {
            Long notTerminated = getEnumItemIdByName("人员枚举", "LanguagePreference", "Simplified Chinese");
            param.put("LanguagePreference", notTerminated);
        }
        return param;
    }

    private BigDecimal longToBigDecimal(Long val) {
        return new BigDecimal(val);
    }

    private Date getActiveDate(String time) {
        if (Strings.isEmpty(time)) {
            return null;
        }
        try {
            Date date = DateUtil.parse(time, "yyyy/MM/dd");
            Date start = DateUtil.parse("1753-01-01", "yyyy-MM-dd");
            Date end = DateUtil.parse("9999-12-31", "yyyy-MM-dd");
            if (date.after(start) && date.before(end)) {
                return date;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            try {
                Date date = DateUtil.parse(time, "yyyy-MM-dd-HH:mm");
                Date start = DateUtil.parse("1753-01-01", "yyyy-MM-dd");
                Date end = DateUtil.parse("9999-12-31", "yyyy-MM-dd");
                if (date.after(start) && date.before(end)) {
                    return date;
                }
            } catch (Exception e1) {
                log.error("##强生客开:", e);
            }
        }
        log.error("##强生客开: 日期小于等于1753-01-01或者大于等于9999-12-31,返回日期null......" + time);
        return null;
    }

    private void map2Member(V3xOrgMember member, FormBean formBean,
                            Map<String, Long> initMap, FormDataMasterBean dataBean, Map<Long, Long> departsAnddeptLeaderMap) {
        member.setCreateTime(new Date());
        member.setUpdateTime(new Date());
        member.setIdIfNew();
        member.setIsAdmin(false);
        member.setIsAssigned(true);
        member.setIsDeleted(false);
        member.setIsInternal(true);
        member.setIsLoginable(true);
        // 默认为正式
        member.setType(1);
        // 默认为在职
        member.setState(1);
        member.setStatus(1);
        member.setEnabled(true);


        String name = "";
        Object property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("LastName").getName());
        name = (property == null ? "" : property.toString());
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("FirstName").getName());
        name += " " + (property == null ? "" : property.toString());
        if (Strings.isEmpty(name.trim())) {
            property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("LastNameinLocalScript").getName());
            name = (property == null ? "" : property.toString());
            property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("FirstNameinLocalScript").getName());
            name += (property == null ? "" : property.toString());
        }

        member.setCode(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("EmployeeID").getName()).toString());
        member.setName(name);
        member.setOrgAccountId(Constants.DEFAULT_ACCOUNT_ID);
        member.setOrgDepartmentId(ParamUtil.getLong(initMap, "dept"));

        if ("LE_MRC_7053_3455".equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("REGION").getName()).toString())
                || "LE_MRC_7076_3432".equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("REGION").getName()).toString())) {
            member.setOrgDepartmentId(ParamUtil.getLong(initMap, "ocd_dept"));
            
            if (isDepartmentManager(departsAnddeptLeaderMap, member.getId()) != null) {
				member.setOrgDepartmentId(isDepartmentManager(departsAnddeptLeaderMap, member.getId()));
			} else {
				if (null != dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName())) {
					String managerWWID = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName()).toString();
					V3xOrgMember manager = baseQiangsDao.getMemberByCode(Constants.DEFAULT_ACCOUNT_ID, "code",
							managerWWID);

					if(manager != null && findDepartment(manager, departsAnddeptLeaderMap, 1) != null) {
						member.setOrgDepartmentId(findDepartment(manager, departsAnddeptLeaderMap, 1));
					}
				}
			}
        } else {
            member.setOrgDepartmentId(ParamUtil.getLong(initMap, "dept"));
        }

        member.setOrgLevelId(ParamUtil.getLong(initMap, "level"));
        member.setOrgPostId(ParamUtil.getLong(initMap, "post"));
        member.setV3xOrgPrincipal(
                dataBean.getFieldValue(formBean.getFieldBeanByDisplay("EmailAddress").getName()).toString().split("@")[0].toLowerCase());

        // 邮件
        member.setProperty("emailaddress",
                dataBean.getFieldValue(formBean.getFieldBeanByDisplay("EmailAddress").getName()).toString().trim());
        // 手机
        member.setProperty("telnumber",
                dataBean.getFieldValue(formBean.getFieldBeanByDisplay("PhoneNumber").getName()));
        // 住址
        member.setProperty("address",
                dataBean.getFieldValue(formBean.getFieldBeanByDisplay("AddressLineData").getName()));
        // 性别
        if (ParamUtil.getString(initMap, "maleId").equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Gender").getName()).toString())) {
            member.setProperty("gender", 1); //男
        } else if (null == dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Gender").getName())) {
            member.setProperty("gender", -1);
        } else {
            member.setProperty("gender", 2); //女
        }
        //直属领导 ManagerWWID
        if (null != dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName())) {
            String managerWWID = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName()).toString();
            V3xOrgMember mmember = baseQiangsDao.getMemberByCode(Constants.DEFAULT_ACCOUNT_ID, "code", managerWWID);
            if (null != mmember) {
                member.setReporter(mmember.getId());
            }
        }
        // 生日
        member.setProperty("birthday",
                (Date) dataBean.getFieldValue(formBean.getFieldBeanByDisplay("BirthDate").getName()));
        //自定义字段 处理 需按加自定义字段排序添加
        // 自定义字段	中文姓名
        Object xing = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("LastNameinLocalScript").getName());
        Object ming = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("FirstNameinLocalScript").getName());
        Object hire = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("HireDate").getName());
        if (null != xing || null != ming || null != hire) {
            List<String> customList = new ArrayList<String>();
            customList.add(null);
            customList.add((xing == null ? "" : xing.toString())
                    + (ming == null ? "" : ming.toString()));
            // 自定义字段	 入职时间
            customList.add(DateUtil.format((Date) hire));
            member.setCustomerAddressBooklist(customList);
        }
    }
    
    private Long isDepartmentManager(Map<Long, Long> departManagerMap, Long id) {
		for(Map.Entry<Long, Long> entry : departManagerMap.entrySet()) {
			if(id.equals(entry.getValue())) {
				return entry.getKey();
			}
		}
		
		return null;
	}
	
	private Long findDepartment(V3xOrgMember manager, Map<Long, Long> departManagerMap,int depth) {
		
		for(Map.Entry<Long, Long> entry : departManagerMap.entrySet()) {
			if(manager.getId().equals(entry.getValue())) {
				return entry.getKey();
			}
		}
		
		//找到managerId的上级managerId
		Long managerReprterId = manager.getReporter();
		V3xOrgMember managerReporter = null;
		try {
			managerReporter = orgManager.getMemberById(managerReprterId);
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		
		if(managerReporter == null) {
			return null;
		}
		
		if(depth <= 6) {
			return findDepartment(managerReporter, departManagerMap,depth+1);
		}
		
		return null;
	}

    private boolean data2UpdateMember(V3xOrgMember member, FormBean formBean,
                                      Map<String, Long> initMap, FormDataMasterBean dataBean, Map<Long, Long> departsAnddeptLeaderMap) {
        boolean isUpdate = false;
        String content = "";
        if (ParamUtil.getString(initMap, "terminated").equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Terminated").getName()).toString())
                && !member.getEnabled()) {
            return false;
        } else if (ParamUtil.getString(initMap, "terminated").equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Terminated").getName()).toString())
                && member.getEnabled()) {
            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("上次同步时间").getName(), DateUtil.currentDate());
            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(), "状态为:Terminated,停用该人员.");
            member.setEnabled(false);
            return true;
        } else if (!ParamUtil.getString(initMap, "terminated").equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Terminated").getName()).toString())
                && !member.getEnabled()) {
            member.setEnabled(true);
            content += "启用人员.";
            isUpdate = true;
        }

        //姓名
        String name = "";
        Object property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("LastName").getName());
        name = (property == null ? "" : property.toString());
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("FirstName").getName());
        name += " " + (property == null ? "" : property.toString());
        if (Strings.isEmpty(name.trim())) {
            property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("LastNameinLocalScript").getName());
            name = (property == null ? "" : property.toString());
            property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("FirstNameinLocalScript").getName());
            name += (property == null ? "" : property.toString());
        }

        if (!member.getName().equals(name)) {
            member.setName(name);
            if (content.contains("此次同步修改了人员的")) {
                content += "、姓名";
            } else {
                content += "此次同步修改了人员的: " + "姓名";
            }
            isUpdate = true;
        }
        // 邮件
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("EmailAddress").getName());
        if (null == property) {
            if (Strings.isNotEmpty(member.getEmailAddress())) {
                member.setProperty("emailaddress", "");
                if (content.contains("此次同步修改了人员的")) {
                    content += "、邮箱地址";
                } else {
                    content += "此次同步修改了人员的: " + "邮箱地址";
                }
                isUpdate = true;
            }
        } else if (!property.equals(member.getEmailAddress())) {
            member.setProperty("emailaddress", property.toString());
            if (content.contains("此次同步修改了人员的")) {
                content += "、邮箱地址";
            } else {
                content += "此次同步修改了人员的: " + "邮箱地址";
            }
            isUpdate = true;
        }

        // 部门(暂时仅对LE_MRC_7053_3455和LE_MRC_7076_3432)
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("REGION").getName());
        if (("LE_MRC_7053_3455".equals(property) || "LE_MRC_7076_3432".equals(property)) && ParamUtil.getLong(initMap, "ocd_dept") != null) {
            member.setOrgDepartmentId(ParamUtil.getLong(initMap, "ocd_dept"));
            
            if (isDepartmentManager(departsAnddeptLeaderMap, member.getId()) != null) {
					member.setOrgDepartmentId(isDepartmentManager(departsAnddeptLeaderMap, member.getId()));
				} else {
					if (null != dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName())) {
						String managerWWID = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName()).toString();
						V3xOrgMember manager = baseQiangsDao.getMemberByCode(Constants.DEFAULT_ACCOUNT_ID, "code",
								managerWWID);

						if(manager != null && findDepartment(manager, departsAnddeptLeaderMap, 1) != null) {
							member.setOrgDepartmentId(findDepartment(manager, departsAnddeptLeaderMap, 1));
						}
					}
				}
            
            if (content.contains("此次同步修改了人员的")) {
                content += "、部门为OCD";
            } else {
                content += "此次同步修改了人员的: " + "部门为OCD";
            }
            isUpdate = true;
        }

        // 手机
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("PhoneNumber").getName());
        if (null == property) {
            if (Strings.isNotEmpty(member.getTelNumber())) {
                member.setProperty("telnumber", "");
                if (content.contains("此次同步修改了人员的")) {
                    content += "、手机号码";
                } else {
                    content += "此次同步修改了人员的: " + "手机号码";
                }
                isUpdate = true;
            }
        } else if (!property.equals(member.getTelNumber())) {
            member.setProperty("telnumber", property.toString());
            if (content.contains("此次同步修改了人员的")) {
                content += "、手机号码";
            } else {
                content += "此次同步修改了人员的: " + "手机号码";
            }
            isUpdate = true;
        }
        // 住址
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("AddressLineData").getName());
        if (null == property) {
            if (Strings.isNotEmpty(member.getAddress())) {
                member.setProperty("address", "");
                if (content.contains("此次同步修改了人员的")) {
                    content += "、地址";
                } else {
                    content += "此次同步修改了人员的: " + "地址";
                }
                isUpdate = true;
            }
        } else if (!property.equals(member.getAddress())) {
            member.setProperty("address", property.toString());
            if (content.contains("此次同步修改了人员的")) {
                content += "、地址";
            } else {
                content += "此次同步修改了人员的: " + "地址";
            }
            isUpdate = true;
        }
        // 性别
        if (null == dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Gender").getName())) {
            if (member.getGender().intValue() != -1) {
                member.setProperty("gender", -1);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、性别";
                } else {
                    content += "此次同步修改了人员的: " + "性别";
                }
                isUpdate = true;
            }
        } else if (ParamUtil.getString(initMap, "maleId").equals(dataBean.getFieldValue(formBean.getFieldBeanByDisplay("Gender").getName()).toString())) {
            if (member.getGender().intValue() != 1) {
                member.setProperty("gender", 1);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、性别";
                } else {
                    content += "此次同步修改了人员的: " + "性别";
                }
                isUpdate = true;
            }
        } else {
            if (member.getGender().intValue() != 2) {
                member.setProperty("gender", 2);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、性别";
                } else {
                    content += "此次同步修改了人员的: " + "性别";
                }
                isUpdate = true;
            }
        }
        // 生日
        Date birthday = (Date) dataBean.getFieldValue(formBean.getFieldBeanByDisplay("BirthDate").getName());
        if (null == birthday) {
            if (null != member.getBirthday()) {
                member.setProperty("birthday", null);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、出生日期";
                } else {
                    content += "此次同步修改了人员的: " + "出生日期";
                }
                isUpdate = true;
            }
        } else {
            if (member.getBirthday() == null) {

            } else if (birthday.compareTo(member.getBirthday()) != 0) {
                member.setProperty("birthday", birthday);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、出生日期";
                } else {
                    content += "此次同步修改了人员的: " + "出生日期";
                }
                isUpdate = true;
            }
        }

        //直属领导
        if (null == dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName())) {
            if (null != member.getReporter()) {
                member.setReporter(null);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、直属领导";
                } else {
                    content += "此次同步修改了人员的: " + "直属领导";
                }
                isUpdate = true;
            }
        } else {
            String managerWWID = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("ManagerWWID").getName()).toString();
            V3xOrgMember mmember = baseQiangsDao.getMemberByCode(Constants.DEFAULT_ACCOUNT_ID, "code", managerWWID);
            if (null != mmember) {
                if (!mmember.getId().equals(member.getReporter())) {
                    member.setReporter(mmember.getId());
                    if (content.contains("此次同步修改了人员的")) {
                        content += "、直属领导";
                    } else {
                        content += "此次同步修改了人员的: " + "直属领导";
                    }
                    isUpdate = true;
                }
            }
        }


        //自定义字段特殊处理
        List<String> customList;
        try {
            customList = getCustomerAddressBooklist(member.getId());
        } catch (BusinessException e) {
            // TODO Auto-generated catch block
            customList = new ArrayList<String>();
        }

        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("LastNameinLocalScript").getName());
        name = (property == null ? "" : property.toString());
        property = dataBean.getFieldValue(formBean.getFieldBeanByDisplay("FirstNameinLocalScript").getName());
        name += (property == null ? "" : property.toString());
        birthday = (Date) dataBean.getFieldValue(formBean.getFieldBeanByDisplay("HireDate").getName());

        if (CollectionUtils.isEmpty(customList)) {
            customList.add(null);
            customList.add(name);
            customList.add(DateUtil.format(birthday));

            if (Strings.isNotBlank(name)) {
                if (content.contains("此次同步修改了人员的")) {
                    content += "、中文姓名";
                } else {
                    content += "此次同步修改了人员的: " + "中文姓名";
                }
                isUpdate = true;
            }

            if (birthday != null) {
                if (content.contains("此次同步修改了人员的")) {
                    content += "、入职日期";
                } else {
                    content += "此次同步修改了人员的: " + "入职日期";
                }
                isUpdate = true;
            }
        } else {
            // 自定义字段	中文姓名
            if (!name.equals(customList.get(1))) {
                customList.set(1, name);
                if (content.contains("此次同步修改了人员的")) {
                    content += "、中文姓名";
                } else {
                    content += "此次同步修改了人员的: " + "中文姓名";
                }
                isUpdate = true;
            }

            // 自定义字段	 入职时间
            if (null == birthday) {
                if (Strings.isNotEmpty(customList.get(2))) {
                    customList.set(2, "");
                    if (content.contains("此次同步修改了人员的")) {
                        content += "、入职日期";
                    } else {
                        content += "此次同步修改了人员的: " + "入职日期";
                    }
                    isUpdate = true;
                }
            } else {
                if (!DateUtil.format(birthday).equals(customList.get(2))) {
                    customList.set(2, DateUtil.format(birthday));
                    if (content.contains("此次同步修改了人员的")) {
                        content += "、入职日期";
                    } else {
                        content += "此次同步修改了人员的: " + "入职日期";
                    }
                    isUpdate = true;
                }
            }
        }
        member.setCustomerAddressBooklist(customList);

        if (isUpdate) {
            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("上次同步时间").getName(), DateUtil.currentDate());
            dataBean.addFieldValue(formBean.getFieldBeanByDisplay("同步操作备注").getName(), content + ".");
        }
        return isUpdate;
    }

    private List<String> getCustomerAddressBooklist(Long memberId) throws BusinessException {
        List<String> list = new ArrayList<String>();
        AddressBook addressBook = addressBookCustomerFieldInfoManager.getByMemberId(memberId);
        List<MetadataColumnBO> metadataColumnList = addressBookManager.getCustomerAddressBookList();
        for (MetadataColumnBO metadataColumn : metadataColumnList) {
            String columnName = metadataColumn.getColumnName();
            try {
                Method method = addressBookManager.getGetMethod(columnName);
                if (null == method) {
                    throw new BusinessException("自定义通讯录字段: " + metadataColumn.getLabel() + "不存在！");
                }
                if (null != addressBook) {
                    Object value = method.invoke(addressBook, new Object[]{});
                    if (metadataColumn.getType() == 0) {//文本
                        String saveValue = null == value ? "" : String.valueOf(value);
                        list.add(saveValue);
//						 list.add(Strings.isNotEmpty(newValue)?newValue:saveValue);
                    }
                    if (metadataColumn.getType() == 1) {//数字
                        if (null == value) {
                            list.add("");
                        } else {
                            BigDecimal bd = new BigDecimal(String.valueOf(value));
                            DecimalFormat df = new DecimalFormat("########.####");
                            list.add(df.format(bd));
//							 list.add(Strings.isNotEmpty(newValue)?newValue:df.format(bd));
                        }
                    }
                    if (metadataColumn.getType() == 2) {//日期
                        String saveValue = null == value ? "" : Datetimes.formatDate((Date) value);
                        list.add(saveValue);
//						 list.add(Strings.isNotEmpty(newValue)?newValue:saveValue);
                    }
                    if (metadataColumn.getType() == 3) {//枚举
                        String saveValue = null == value ? "" : String.valueOf(value);
                        list.add(saveValue);
//						 list.add((Strings.isNotEmpty(newValue) && !"-1".equals(newValue))?newValue:saveValue);
                    }
                    if (metadataColumn.getType() == 4) {//选人
                        String saveValue = null == value ? "" : String.valueOf(value);
                        list.add(saveValue);
//						 list.add((Strings.isNotEmpty(newValue) && !"-1".equals(newValue))?newValue:saveValue);
                    }
                    if (metadataColumn.getType() == 5) {//选部门
                        String saveValue = null == value ? "" : String.valueOf(value);
                        list.add(saveValue);
//						 list.add((Strings.isNotEmpty(newValue) && !"-1".equals(newValue))?newValue:saveValue);
                    }
                } else {
                    list.add("");
                }
            } catch (Exception e) {
                log.error("##强生客开: ", e);
            }
        }
        return list;
    }


	@Override
    public String convertDealTime(Date startDate, Date currentDate, Long accountId)
            throws BusinessException {
        // TODO Auto-generated method stub
    	String ret = "";
        long time = workTimeManager.getDealWithTimeValue(startDate, currentDate, accountId);
        time = time / (60 * 1000); //毫秒转化为分钟
        if(Math.abs(time) != time){
        	ret = "-";
        	time = Math.abs(time);
        }
        long day = time / (24 * 60);
        if(0 != day){
        	ret += day + "天";
        }
        long hous = (time % (24 * 60)) / 60;
        if(0 != hous){
        	ret += hous + "时";
        }
        time = (time % (24 * 60)) % 60;
        ret += time + "分";
        return ret;
    }

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	public void setBaseQiangsDao(SyncOrgDao baseQiangsDao) {
		this.baseQiangsDao = baseQiangsDao;
	}

	public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
		this.formApi4Cap4 = formApi4Cap4;
	}

	public void setEnumManagerNew(EnumManager enumManagerNew) {
		this.enumManagerNew = enumManagerNew;
	}

	public void setConfigManager(ConfigManager configManager) {
		this.configManager = configManager;
	}

	public void setWorkTimeManager(WorkTimeManager workTimeManager) {
		this.workTimeManager = workTimeManager;
	}

	public void setOrgManagerDirect(OrgManagerDirect orgManagerDirect) {
		this.orgManagerDirect = orgManagerDirect;
	}

	public void setKkBaseFormManager(FormDataBaseManager kkBaseFormManager) {
		this.kkBaseFormManager = kkBaseFormManager;
	}

	public void setAddressBookManager(AddressBookManager addressBookManager) {
		this.addressBookManager = addressBookManager;
	}

	public void setAddressBookCustomerFieldInfoManager(
			AddressBookCustomerFieldInfoManager addressBookCustomerFieldInfoManager) {
		this.addressBookCustomerFieldInfoManager = addressBookCustomerFieldInfoManager;
	}
	
	
}
